//
//  RegisterViewController.swift
//  Copy_Aikaopu
//
//  Created by taojianz on 2017/6/28.
//  Copyright © 2017年 taojianz. All rights reserved.
//

import UIKit

class RegisterViewController: BaseViewController {

    var iconView : UIButton!
    
    var femaleBtn : UIButton!
    
    var maleBtn : UIButton!
    
    var nickNameField : UnderLineTextField!
    
    var birthField : UnderLineTextField!
    
    var regionField : UnderLineTextField!
//     birthField.inputView
    var datePicker : UIDatePicker!
    
    var datePickerToolBar : UIToolbar!
//     regionField.inputView
    var cityPicker : CityPickerView!
    
    var cityPickerToolBar : UIToolbar!
    
    
    
    
    var confirmBtn : UIButton!
    // 选中的性别
    var selectedSex : String?
    // 选中的头像
    var selectedIcon : UIImage?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "完善个人信息"
      
    }


}
// MARK： setupUI
extension RegisterViewController{
    override func setupUI() {
        super.setupUI()
        
        setupIconImageView()
        setupSexBtn()
        setupInputView()
        setupConfirmBtn()
        
    }
    func setupIconImageView(){
        self.iconView = UIButton()
        
        iconView.setBackgroundImage(#imageLiteral(resourceName: "头像"), for: .normal)
        iconView.layer.cornerRadius = 50
        iconView.clipsToBounds = true
        
        view.addSubview(iconView)
        
        iconView.snp.makeConstraints { (maker) in
            maker.top.equalToSuperview().offset(64+20)
            maker.centerX.equalToSuperview()
            maker.height.width.equalTo(100)
        }
        
        
        iconView.addTarget(self, action: #selector(userIconViewTapped), for: .touchUpInside)
        
    }
    func setupSexBtn(){
        // 距离视图中心线的距离
        let margin : CGFloat = 18
        
        // 女性按钮
        self.femaleBtn =  UIButton()
        
        femaleBtn.setImage(#imageLiteral(resourceName: "nv"), for: .normal)
        femaleBtn.setImage(#imageLiteral(resourceName: "nvxuanzhong"), for: .selected)
        femaleBtn.tag = 100
        
        femaleBtn.addTarget(self, action: #selector(sexBtnTapped(sender:)), for: .touchUpInside)
        
        view.addSubview(femaleBtn)
        
        femaleBtn.snp.makeConstraints { (maker) in
            maker.top.equalTo(iconView.snp.bottom).offset(18)
            maker.right.equalTo(view.snp.centerX).offset(-margin)
        }
        
        // 男性按钮
        self.maleBtn = UIButton()
        
        maleBtn.setImage(#imageLiteral(resourceName: "nan"), for: .normal)
        maleBtn.setImage(#imageLiteral(resourceName: "nanxuanzhong"), for: .selected)
        maleBtn.tag = 101
        
        maleBtn.addTarget(self, action: #selector(sexBtnTapped(sender:)), for: .touchUpInside)
        
        view.addSubview(maleBtn)
        
        maleBtn.snp.makeConstraints { (maker) in
            maker.centerY.equalTo(femaleBtn.snp.centerY)
            maker.left.equalTo(view.snp.centerX).offset(margin)
        }
        
    }
    
    func setupInputView(){
        // 昵称图标
        let nickIcon = UIImageView(image: #imageLiteral(resourceName: "gerenxinxiyonghu"))
        
        view.addSubview(nickIcon)
        
        nickIcon.snp.makeConstraints { (maker) in
            maker.top.equalTo(maleBtn.snp.bottom).offset(18)
            maker.left.equalToSuperview().offset(28)
        }
        
        // 昵称输入框
        self.nickNameField = UnderLineTextField(frame:CGRect(x: 50, y: 200, width: view.frame.width/4*3, height: nickIcon.frame.height+2))
        
        nickNameField.textField.placeholder = "昵称"
        
        view.addSubview(nickNameField)
        
        nickNameField.snp.makeConstraints { (maker) in
            maker.right.equalToSuperview().offset(-40)
            maker.left.equalTo(nickIcon.snp.right).offset(8)
            maker.centerY.equalTo(nickIcon.snp.centerY)
            maker.height.equalTo(nickIcon.snp.height)
        }
        
        // TODO: 更改 textField 的 inputView
        // TODO: 获取pickerView中选中的值
        // 生日图标
        let birIcon = UIImageView(image: #imageLiteral(resourceName: "liwu"))
        
        view.addSubview(birIcon)
        
        birIcon.snp.makeConstraints { (maker) in
            maker.centerX.equalTo(nickIcon.snp.centerX)
            maker.top.equalTo(nickIcon.snp.bottom).offset(18)
        }
        // 生日输入框
        self.birthField = UnderLineTextField(frame:CGRect(x: 50, y: 200, width: view.frame.width/4*3, height: nickIcon.frame.height+2))
        
        birthField.textField.placeholder = "选择生日"
        
        view.addSubview(birthField)
        
        // 初始化pickerView
        setupPickerView()
        
        // 设置birthField.textfield的inputView
        birthField.textField.inputView = self.datePicker
        // 设置birthField.textfield的toolBar
        birthField.textField.inputAccessoryView = datePickerToolBar
        
        birthField.snp.makeConstraints { (maker) in
            maker.right.equalToSuperview().offset(-40)
            maker.left.equalTo(birIcon.snp.right).offset(8)
            maker.centerY.equalTo(birIcon.snp.centerY)
            maker.height.equalTo(birIcon.snp.height)
        }
        // 地区图标
        let regionIcon = UIImageView(image: #imageLiteral(resourceName: "liwu"))
        
        view.addSubview(regionIcon)
        
        regionIcon.snp.makeConstraints { (maker) in
            maker.centerX.equalTo(birIcon.snp.centerX)
            maker.top.equalTo(birIcon.snp.bottom).offset(18)
        }
        
        // 地区输入框
        self.regionField = UnderLineTextField(frame:CGRect(x: 50, y: 200, width: view.frame.width/4*3, height: nickIcon.frame.height+2))
        
        regionField.textField.placeholder = "选择你的地区"
        
        // 改变地区输入框的inputView
        regionField.textField.inputView = self.cityPicker
        regionField.textField.inputAccessoryView = cityPickerToolBar
        
        view.addSubview(regionField)
        
        regionField.snp.makeConstraints { (maker) in
            maker.right.equalToSuperview().offset(-40)
            maker.left.equalTo(regionIcon.snp.right).offset(8)
            maker.centerY.equalTo(regionIcon.snp.centerY)
            maker.height.equalTo(regionIcon.snp.height)
        }
    }
    
    func setupConfirmBtn(){
        let textLabel = UILabel()
        
        textLabel.text = "注册成功后，性别生日不可修改"
        textLabel.font = UIFont.systemFont(ofSize: 11)
        textLabel.textColor = UIColor.darkText
        
        view.addSubview(textLabel)
        
        textLabel.snp.makeConstraints { (maker) in
            maker.top.equalTo(regionField.snp.bottom).offset(30)
            maker.centerX.equalToSuperview()
        }
        
        // 下一步按钮
        // TODO: 点击下一步判断填写是否完成，完成之后进入下一步，未完成则弹popview
        self.confirmBtn = UIButton(type: .system)
        
        confirmBtn.backgroundColor = .red
        confirmBtn.setTitle("下一步", for: .normal)
        confirmBtn.setTitleColor(.white, for: .normal)
        confirmBtn.layer.cornerRadius = 5
        view.addSubview(confirmBtn)
        
        confirmBtn.snp.makeConstraints { (maker) in
            maker.top.equalTo(textLabel.snp.bottom).offset(3)
            maker.centerX.equalToSuperview()
            maker.left.equalToSuperview().offset(18)
            maker.right.equalToSuperview().offset(-18)
            maker.height.equalTo(40)
        }
    }
    
}

// MARK: 按钮的点击事件
extension RegisterViewController{
    // 性别按钮的点击事件
    func sexBtnTapped(sender : UIButton){
        switch sender.tag {
        case 100:
            sender.isSelected = !sender.isSelected
            maleBtn.isSelected = false
        case 101:
            sender.isSelected = !sender.isSelected
            femaleBtn.isSelected = false
        default:
            break
        }
        selectedSex = (femaleBtn.isSelected) ? "女" : "男"
    }
    func userIconViewTapped(){
        let alertVC = UIAlertController(title: "需上传本人真实头像", message: nil, preferredStyle: .actionSheet)
        // TODO: 启动摄像头
        let cameraAction = UIAlertAction(title: "拍照", style: .default){ (_) in
            self.openCamera()
        }
        let albumAction = UIAlertAction(title: "从手机相册选取", style: .default) { (_) in
            self.chooseAlbumImage()
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertVC.addAction(cameraAction)
        alertVC.addAction(albumAction)
        // FIXME: why 添加取消之后点击灰色视图能取消actionsheet
        alertVC.addAction(cancelAction)
        
        present(alertVC, animated: true, completion: nil)
    }
    func setupPickerView(){
        // toolbar的占位item
        let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        // 日期选择
        self.datePicker = UIDatePicker()
        
        datePicker.datePickerMode = .date
        
        datePicker.locale = Locale(identifier: "zh")
        datePicker.maximumDate = Date.init(timeIntervalSinceNow: 0)
        
        self.datePickerToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 44))
        
        // TODO: 点击完成将 picker 的结果输入到field
        let dateFinishBtn = UIBarButtonItem(title: "完成", style: .done, target: self, action:#selector(resignTextField))
        datePickerToolBar.items = [spaceItem,dateFinishBtn]
        dateFinishBtn.tintColor = .red
        
        // 城市选择
        self.cityPicker = CityPickerView()
        
        self.cityPickerToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 44))
        
        let cityFinishBtn = UIBarButtonItem(title: "完成", style: .done, target: self, action:#selector(resignTextField))
        cityPickerToolBar.tintColor = .red
        
        cityPickerToolBar.items = [spaceItem , cityFinishBtn]
        
    }
    
}
// MARK: 选择个人头像
extension RegisterViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    // 选择相册图片
    func chooseAlbumImage(){
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary)else{
            print("无法获得相册授权")
            return
        }
        let picker = UIImagePickerController()
        
        picker.allowsEditing = true // 允许用户编辑图片
        picker.sourceType = .photoLibrary
        picker.delegate = self
        
        self.present(picker, animated: true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
            print("无法获取选中图片")
            return
        }
        self.selectedIcon = image
        
        self.iconView.setImage(image, for: .normal)
        
        iconView.imageView?.contentMode = .scaleToFill
        iconView.imageView?.clipsToBounds = true
        
        dismiss(animated: true, completion: nil)
    }
    // 拍照
    func openCamera(){
        guard UIImagePickerController.isSourceTypeAvailable(.camera)else{
            print("无法获得相册授权")
            return
        }
        let picker = UIImagePickerController()
        
        picker.allowsEditing = true // 允许用户编辑图片
        picker.sourceType = .camera
        picker.delegate = self
        
        // 如果前置摄像头有用则开启前置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.front){
            picker.cameraDevice = UIImagePickerControllerCameraDevice.front
        }
        
        self.present(picker, animated: true, completion: nil)
    }
    // pickerView消失
    func resignTextField(){
        self.view.endEditing(true)
    }
    
    func finishDatePicker(){
        
        self.view.endEditing(true)
    
    }
    
    func finishRegionPicker(){
        
        self.view.endEditing(true)
        
        
        
        
    }
}




























